import { createStore } from "vuex";
import { setToken, getToken } from "~/composables/auth";

const store = createStore({
  state() {
    return {
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      token: getToken() || ""
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      setToken(token);
    },
    SET_USERINFO(state, user) {
      state.user = { ...state.user, ...user };
      localStorage.setItem('user', JSON.stringify(state.user));
    },
    LOAD_FROM_LOCAL_STORAGE(state) {
      const user = localStorage.getItem('user');
      if (user) state.user = JSON.parse(user);
    }
  },
  actions: {
    // 模拟登录 action
    // 11.讲解
    async login({ commit }, { id, password, type }) {
      try {
        // 调用模拟的登录请求
        const res = await {
          post: (url) => new Promise((resolve) => {
            if (password === '123456') {
              resolve({
                token: 'mock_token',
                data: { id, password, type }
              });
            } else {
              throw new Error('账号或密码错误');
            }
          })
        }.post('/login');
        
        commit("SET_TOKEN", res.token);
        commit("SET_USERINFO", { id, password, type });
        return res;
      } catch (err) {
        const errorMsg = err.message || '登录失败：账号或密码错误';
        // 假设你有 toast 方法，这里模拟提示
        console.error(errorMsg);
        throw err;
      }
    },
    // 模拟获取用户信息 action
    async getinfo({ commit }) {
      try {
        const res = await {
          get: (url) => new Promise((resolve) => {
            const user = JSON.parse(localStorage.getItem('user') || '{}');
            resolve({
              code: 200,
              data: { ...user, mockInfo: '模拟信息' }
            });
          })
        }.get(`/info/${this.state.user.type}/${this.state.user.id}`);
        
        commit("SET_USERINFO", res.data);
        return res;
      } catch (err) {
        console.error('获取用户信息失败（模拟）', err);
        throw err;
      }
    },
    // 模拟更新用户信息 action
    async updateinfo({ commit }, updatedInfo) {
      try {
        const res = await {
          put: (url) => new Promise((resolve) => {
            const user = JSON.parse(localStorage.getItem('user') || '{}');
            const newUser = { ...user, ...updatedInfo };
            localStorage.setItem('user', JSON.stringify(newUser));
            resolve({
              code: 200,
              data: newUser
            });
          })
        }.put(`/info/${this.state.user.type}/${this.state.user.id}`, updatedInfo);
        
        commit("SET_USERINFO", res.data);
        return res;
      } catch (err) {
        console.error('更新用户信息失败（模拟）', err);
        throw err;
      }
    },
    // 模拟修改密码 action（前端本地修改）
    async updatePassword({ commit }, newPassword) {
      try {
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        user.password = newPassword;
        localStorage.setItem('user', JSON.stringify(user));
        commit("SET_USERINFO", user);
        return { data: { message: '密码修改成功' } };
      } catch (err) {
        console.error('修改密码失败（模拟）', err);
        throw err;
      }
    }
  }
});

store.commit('LOAD_FROM_LOCAL_STORAGE');
export default store;